package com.xindacloud.sms.adapter.service.sms.impl;

import com.clxcommunications.xms.ApiConnection;
import com.clxcommunications.xms.ClxApi;
import com.clxcommunications.xms.api.MtBatchTextSmsCreate;
import com.clxcommunications.xms.api.MtBatchTextSmsResult;
import com.clxcommunications.xms.api.ReportType;
import com.xindacloud.sms.adapter.bo.SubmitMessageBO;
import com.xindacloud.sms.adapter.constant.CommonConstant;
import com.xindacloud.sms.adapter.exception.ServiceException;
import com.xindacloud.sms.adapter.service.factory.SinchClientFactory;
import com.xindacloud.sms.adapter.service.sms.ISubmitMessageService;
import com.xindacloud.sms.adapter.utils.UnionResultHelp;
import com.xindacloud.sms.adapter.vo.SubmitMessageResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Objects;

@Service("sinchSubmitMessageService")
@Slf4j
public class SinchSubmitMessageServiceImpl implements ISubmitMessageService<SubmitMessageBO, SubmitMessageResultVO> {


    private final SinchClientFactory sinchClientFactory;


    @Autowired
    public SinchSubmitMessageServiceImpl(SinchClientFactory sinchClientFactory) {
        this.sinchClientFactory = sinchClientFactory;
    }


    @Override
    public SubmitMessageResultVO submitMessage(SubmitMessageBO submitMessageBO) {

        final String recipient = submitMessageBO.getRecipient();
        final String apiSecret = submitMessageBO.getApiSecret();
        final String apiUrl = submitMessageBO.getApiUrl();
        final String apiKey = submitMessageBO.getApiKey();
        final String senderId = submitMessageBO.getSenderId();
        final String messageBody = submitMessageBO.getMessageBody();
        final String callBackUrl = submitMessageBO.getCallBackUrl();
        ApiConnection apiConnection = null;
        try {

            apiConnection = sinchClientFactory.getSinchClient(apiKey, apiSecret, apiUrl);
            MtBatchTextSmsCreate.Builder builder = ClxApi.batchTextSms().sender(senderId).body(messageBody);
            String[] splitRecipients = recipient.split(CommonConstant.SEPARATOR_STR);
            if (splitRecipients.length > 1) {
                builder.addAllRecipients(Arrays.asList(splitRecipients));
            } else {
                builder.addRecipient(recipient);
            }
            builder.deliveryReport(ReportType.FULL);
            builder.callbackUrl(new URI(callBackUrl));
            MtBatchTextSmsResult result = apiConnection.createBatch(builder.build());
            return SubmitMessageResultVO.builder()
                    .errorText("")
                    .messageId(result.id().toString())
                    .network("")
                    .submitStatus(0)
                    .build();
        } catch (Exception e) {
            log.error("Sinch发送短信异常:{}", e.getMessage(), e);
            throw new ServiceException("短信发送异常:".concat(e.getMessage()), UnionResultHelp.StatusEnum.BadRequest.code());
        } finally {
            try {
                if (Objects.nonNull(apiConnection)) {
                    apiConnection.close();
                }
            } catch (IOException e) {
                log.error("关闭Sinch连接异常:{}", e.getMessage(), e);
            }
        }
    }

}
